package com.yunshang.shoppingmall.common;


import com.yunshang.shoppingmall.Methods.FinaceMethods;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;

@Component
public class OrderHelper {
    @Autowired
    private FreightService freightService1;
    private static FreightService freightService;

    @Autowired
    private AddressService addressService1;
    private static AddressService addressService;

    @Autowired
    private CartService cartService1;
    private static CartService cartService;

    @Autowired
    private ConfigService configService1;
    private static ConfigService configService;
    @Autowired
    private ProductService productService1;
    private static ProductService productService;
    @PostConstruct
    public void init() {freightService=freightService1;addressService=addressService1;cartService=cartService1;configService=configService1;productService=productService1;}

    public static Boolean checkArea(String provinceId,String areaIds){
        boolean bools=false;
        String []strs=areaIds.split(",");
        for (String str:strs){
            if(str.equals(provinceId)){
                bools=true;
                break;
            }
        }
        return bools;
    }
    //获取运费 订单运费
//    public static Double GetFreight(String ids,Double weight,Integer productCount,Double weightAll){
    public static Double GetFreight(List<FreightData> freightDataList){
        List<Freight> listX=freightService.selectAll();//所有基础运费信息
        double freightDouble=0,freightDouble1=0;
        Boolean boolbreak=false;
        List<Freight> list1=listX.stream().filter(c ->(c.getGuigeId()!=null)).collect(Collectors.toList());
        List<FreightData> freightDatax=freightDataList;
        for (int lm = 0; lm <freightDataList.size() ; lm++) {
            FreightData freightDataX=freightDataList.get(lm);
            int guigeId=freightDataX.getGuigeId()==null?-1:freightDataX.getGuigeId();
            //double weight=freightDataX.getWeight();
            int number=freightDataX.getNumber()==null?0:freightDataX.getNumber();
            //double weightAll=freightDataX.getWeightAll();
            String provinceId=freightDataX.getProvinceId()==null?"0":freightDataX.getProvinceId().toString();
            for (int lk = 0; lk <list1.size() ; lk++) {
                Freight freightX=list1.get(lk);
                String areaIds=freightX.getAreaids();
                int areaNo=freightX.getAreano()==null?0:freightX.getAreano();
                int guigeIdF=freightX.getGuigeId()==null?0:freightX.getGuigeId();
                int increment=freightX.getIncrement()==null?0:freightX.getIncrement();
                //int notFirstWeightOne = freightX.getNotFirstWeightOne() == null ? 0 : freightX.getNotFirstWeightOne();
                //int notFirstWeight = freightX.getNotFirstWeight() == null ? 0 : freightX.getNotFirstWeight();
                //double notFirstWeightPrice = freightX.getNotFirstWeightPrice() == null ? 0 : freightX.getNotFirstWeightPrice();
                //int firstWeight = freightX.getFirstWeight() == null ? 0 : freightX.getFirstWeight();
                double constant = freightX.getConstant() == null ? 0 : freightX.getConstant();
                System.out.println("provinceId:"+provinceId+"areaIds:"+areaIds);
                System.out.println("guigeIdF:"+guigeIdF+"guigeId:"+guigeId);
                System.out.println("freightX:"+freightX.toString());
                System.out.println("freightDataX:"+freightDataX.toString());
                if(checkArea(provinceId,areaIds)==true&&guigeId==guigeIdF&&areaNo<0){
                    System.out.println("存在1");
                    freightDouble +=increment*number;
                    freightDatax.remove(freightDataX);
                    break;
                }
                if(checkArea(provinceId,areaIds)==false&&guigeId==guigeIdF&&areaNo<0){
                    System.out.println("存在2");
                    freightDouble +=constant*number;
                    freightDatax.remove(freightDataX);
                    break;
                }
                if(checkArea(provinceId,areaIds)==false&&guigeId==guigeIdF&&areaNo!=0){
                    System.out.println("存在");
                    freightDouble +=increment*number;
                    freightDatax.remove(freightDataX);
                    break;
                }
                System.out.println("cc:"+guigeId+" st:"+checkArea(provinceId,areaIds));
            }
        }
        System.out.println("freightDouble1:"+freightDouble1);
        for (int h = 0; h <freightDatax.size() ; h++) {
            FreightData freightDataX=freightDatax.get(h);
            int guigeId=freightDataX.getGuigeId()==null?0:freightDataX.getGuigeId();
            double weight=freightDataX.getWeight()==null?0:freightDataX.getWeight();
            int number=freightDataX.getNumber()==null?0:freightDataX.getNumber();
            double weightAll=freightDataX.getWeightAll()==null?0:freightDataX.getWeightAll();
            String provinceId=freightDataX.getProvinceId()==null?"0":freightDataX.getProvinceId().toString();
            for (int v = 0; v <listX.size() ; v++) {
                Freight freightX=listX.get(v);
                String areaIds=freightX.getAreaids();
                int areaNo=freightX.getAreano()==null?0:freightX.getAreano();
                int guigeIdF=freightX.getGuigeId()==null?0:freightX.getGuigeId();
                int increment=freightX.getIncrement()==null?0:freightX.getIncrement();
                int notFirstWeightOne = freightX.getNotFirstWeightOne() == null ? 0 : freightX.getNotFirstWeightOne();
                int notFirstWeight = freightX.getNotFirstWeight() == null ? 0 : freightX.getNotFirstWeight();
                double notFirstWeightPrice = freightX.getNotFirstWeightPrice() == null ? 0 : freightX.getNotFirstWeightPrice();
                int firstWeight = freightX.getFirstWeight() == null ? 0 : freightX.getFirstWeight();
                double constant = freightX.getConstant() == null ? 0 : freightX.getConstant();
                System.out.println("guigeId:"+guigeId+" guigeIdF:"+guigeIdF+" bool:"+checkArea(provinceId,areaIds)+" areaNo:"+areaNo);
                if(checkArea(provinceId,areaIds)==true&&areaNo==0&&guigeId==guigeIdF){
                    System.out.println("f1:"+(weight*number)*increment);
                    freightDouble +=number*increment;
                    boolbreak = true;
                    break;
                }else if(checkArea(provinceId,areaIds)==true&&areaNo==4){//特殊地区收取运费 4区
                    System.out.println("q1:"+(weight*number)*increment);
                    freightDouble +=(weight*number)*increment;
                    boolbreak = true;
                    break;
                }else if (checkArea(provinceId,areaIds)==true&&notFirstWeightOne < weightAll && notFirstWeight >= weightAll) {
                    System.out.println("q2："+notFirstWeightPrice);
                    freightDouble += notFirstWeightPrice;
                    boolbreak = true;
                    break;
                }else if (checkArea(provinceId,areaIds)==true&&weightAll > firstWeight && firstWeight > 0) {

                    Double weightInt = Math.ceil(weightAll);//向上取整 ex：15.01为16
                    System.out.println("q3:"+notFirstWeightPrice + (increment * (weightInt - firstWeight)) + constant);
                    boolbreak = true;
                    freightDouble += notFirstWeightPrice + (increment * (weightInt - firstWeight)) + constant;
                    break;
                }
            }
        }
        System.out.println("frice:"+freightDouble);
        return freightDouble;
    }

    //折扣券抵扣
    public static Integer discount(Integer levelId, Integer m1, Integer m2, Integer m3, Integer m4, Integer m5) {
        //代金券修改为一个定值 暂定使用优质店主的代金券抵扣值
        Integer cashCoupon = 0;
//        switch (levelId) {
//            case 19://游客
//                cashCoupon = m1;
//                break;
//            case 16://会员
//                cashCoupon = m2;
//                break;
//            case 17://店主
//                cashCoupon = m3;
//                break;
//            case 18://优质店主
        cashCoupon = m4;
//                break;
//            case 20://其它
//                cashCoupon = m5;
//                break;
//        }
        return  cashCoupon;
    }

    /**
     组装确认订单数据
     */
    public static Map<String,Object> operOrderDetailsProduct(List<OrderDetailsProduct> list,Integer levelId,Integer userId) {

        Map<String,Object> map=new HashMap<>();
        double weight=0.0;//重量
        Double commission=0.00;//提成比
        double realPay=0.0;//实际支付
        double backCashCoupon=0.0;//返代金券
        Integer productNumber=0;//前端页面显示商品总数量
        DecimalFormat df = new DecimalFormat("#0.00");//显示格式
        Integer realCashCouponS=0;//总的折扣券
        Double couponS=0.00;//总的购物换券
        Double kouchuCoupon=0.00;//扣除已经抵扣的-兑换券
        Double kouchuCashCoupon=0.00;//扣除已经抵扣的-折扣券
        Double tempCoupon=0.00;
        Integer tempRealCashCoupon=0;
        Double memberSaveS=0.00;//会员节省

//        Double avgCoupon= FinaceMethods.getUserBalance(userId,2).doubleValue();//兑换券  用户兑换券余额
        FinaceTotal  finaceTotal= new FinaceTotal();
        finaceTotal.setfType("2");
        finaceTotal.setUserId(userId);
        Double avgCoupon=0.00;
        FinaceTotal finaceTotals = FinaceMethods.selectFinaceBalace(finaceTotal);//兑换券  用户兑换券余额
        if(finaceTotals!=null){
            avgCoupon=finaceTotals.getBalance();
        }
        Double avgCoupon1=avgCoupon;
//        Double avgCashCoupon=FinaceMethods.getUserBalance(userId,3).doubleValue();//折扣券 用户兑换券余额
        finaceTotal.setfType("3");
        Double avgCashCoupon=0.00;
        Address address=new Address();
        double freight=0.00;
        Config config=new Config();
        Config cc=new Config();
        FinaceTotal finaceTotals2 =FinaceMethods.selectFinaceBalace(finaceTotal);//折扣券 用户兑换券余额
        if(finaceTotals2!=null){
            avgCashCoupon=finaceTotals2.getBalance();
        }

        address=addressService.selectDefault(1,userId);//获取默认地址
        int provinceId=0;
        if(address!=null){
            provinceId=address.getProvinceId();
        }
        Double avgCashCoupon1=avgCashCoupon;
        String CartIds="";
        int isMoreAddress=0;//产品是否可以多地址
        int addressCount=0;//最多几个地址
        List<FreightData> listGuiGe=new ArrayList<>();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                //System.out.println("list.size()"+list.get(i).toString());
                OrderDetailsProduct odp=list.get(i);
                //System.out.println("odp:"+odp);
                double weightSS=0;
                if(odp!=null){
                    int ss1=odp.getIsMoreAddress()==null?0:odp.getIsMoreAddress();
                    int ss=odp.getAddressCount()==null?0:odp.getAddressCount();
                    if(ss1>0){
                        isMoreAddress=ss1;
                    }
                    if(ss>0){
                        addressCount=ss;
                    }
                    if(odp.getProWeight()!=null){
                        weightSS=odp.getProWeight();
                    }
                }
                //运费
                FreightData freightData=new FreightData();
                //System.out.println("odp.getGuigeId()"+odp.getGuigeId());
                freightData.setGuigeId(odp.getGuigeId());
                freightData.setNumber(odp.getProductCount());
                freightData.setWeight(odp.getProWeight());
                freightData.setProvinceId(provinceId);
                freightData.setWeightAll(weightSS*odp.getProductCount());
                listGuiGe.add(freightData);
                //运费

                weight +=weightSS*odp.getProductCount();
                Integer visitor = (odp.getVisitor()==null)?0:odp.getVisitor();
                Integer huiyuan = (odp.getHuiyuan()==null)?0:odp.getHuiyuan();
                Integer dianzhu = (odp.getDianzhu()==null)?0:odp.getDianzhu();
                Integer yzDianzhu =(odp.getYzDianzhu()==null)?0:odp.getYzDianzhu();
                Integer otherRank = (odp.getOtherRank()==null)?0:odp.getOtherRank();
                Integer productCount = odp.getProductCount();
                double productPrice = (odp.getProductPrice()==null)?0:odp.getProductPrice().doubleValue();
                double productCost = (odp.getProductCost()==null)?0:odp.getProductCost().doubleValue();
                double pratorCost = (odp.getOpratorCost()==null)?0:odp.getOpratorCost().doubleValue();
                double coupon = (odp.getCoupon()==null)?0:odp.getCoupon().doubleValue();
                if(odp.getCommission()!=null){
                    commission = odp.getCommission() / 100;
                }
                int activeSign=odp.getActiveSign();
                productNumber +=productCount;
                //根据会员等级计算抵扣折扣券
                Integer realCashCoupon = discount(levelId, visitor, huiyuan, dianzhu, yzDianzhu, otherRank);
                odp.setRealCashCoupon(realCashCoupon);
                //计算会员节省
                Double memberSave = 0.00;
                //
                realCashCouponS +=realCashCoupon*productCount;//订单总的折扣券
                couponS +=coupon*productCount;//订单总的兑换券
                //System.out.println("---------------"+couponS);
                //减去扣除
                avgCoupon=avgCoupon-kouchuCoupon;
                avgCashCoupon=avgCashCoupon-kouchuCashCoupon;
                tempCoupon=tempCoupon-kouchuCoupon;
                tempRealCashCoupon=tempRealCashCoupon-kouchuCashCoupon.intValue();
                //
                if (avgCoupon == 0 && avgCashCoupon != 0) {
                    if(avgCashCoupon<realCashCouponS)
                    {
                        tempRealCashCoupon=avgCashCoupon.intValue();
                    }
                    else {
                        tempRealCashCoupon=realCashCoupon*productCount;
                    }
                    memberSave = (productPrice*productCount - productCost*productCount - pratorCost*productCount - tempRealCashCoupon) * commission;
                    kouchuCashCoupon +=tempRealCashCoupon.doubleValue();//赋值扣除
                } else if (avgCashCoupon == 0 && avgCoupon != 0) {
                    if(avgCoupon<couponS){
                        tempCoupon=avgCoupon;
                    }else {
                        tempCoupon=coupon*productCount;
                    }
                    memberSave = (productPrice*productCount - productCost*productCount - pratorCost*productCount - tempCoupon) * commission;
                    kouchuCoupon +=tempCoupon;//赋值扣除
                } else if (avgCashCoupon != 0 && avgCoupon != 0) {
                    if(avgCashCoupon<realCashCouponS&&avgCoupon<couponS) {
                        tempRealCashCoupon=avgCashCoupon.intValue();tempCoupon=avgCoupon;
                    }else if(avgCashCoupon<realCashCouponS&&avgCoupon>=couponS) {
                        tempRealCashCoupon=avgCashCoupon.intValue();tempCoupon=coupon*productCount;
                    }else if(avgCashCoupon>=realCashCouponS&&avgCoupon<couponS) {
                        tempCoupon=avgCoupon;tempRealCashCoupon=realCashCoupon*productCount;
                    }else if (avgCashCoupon>=realCashCouponS&&avgCoupon>=couponS) {
                        tempRealCashCoupon=realCashCoupon*productCount;
                        tempCoupon=coupon*productCount;
                    }
                    memberSave = (productPrice*productCount - productCost*productCount - pratorCost*productCount - tempCoupon - tempRealCashCoupon) * commission;
                    kouchuCashCoupon +=tempRealCashCoupon.doubleValue();//赋值扣除
                    kouchuCoupon +=tempCoupon;//赋值扣除
                } else if (avgCashCoupon == 0 && avgCoupon == 0) {
                    memberSave = (productPrice - productCost - pratorCost)*productCount * commission;
                }
//                    realPay +=productPrice*productCount-tempCoupon-tempRealCashCoupon-memberSave;
                //除零售专区以外的所有专区均没有返折扣券,没有会员节省
//                if(activeSign==4){
                    backCashCoupon +=productPrice*productCount-tempCoupon-tempRealCashCoupon-memberSave;
                    memberSaveS +=memberSave;
                    realPay +=productPrice*productCount-tempCoupon-tempRealCashCoupon-memberSave;
//                }
//                else {
//                    realPay +=productPrice*productCount-tempCoupon-tempRealCashCoupon;
//                }
//                if(activeSign==4){
//                    backCashCoupon +=productPrice*productCount-tempCoupon-tempRealCashCoupon-memberSave;
//                    System.out.println("返折扣券"+backCashCoupon);
//                    memberSaveS +=memberSave;
//                    realPay +=productPrice*productCount-tempCoupon-tempRealCashCoupon-memberSave;
//                }
//                else {
//                    realPay +=productPrice*productCount-tempCoupon-tempRealCashCoupon;
//                }
//                memberSaveS +=memberSave;
                if(i<list.size()-1){
                    CartIds +=odp.getShoppingId()+",";
                }else {
                    CartIds +=odp.getShoppingId();
                }
            }
            //freight= OrderHelper.GetFreight(provinceId+"",weight);
            freight= OrderHelper.GetFreight(listGuiGe);
            config= configService.selectByPrimaryKey(1);//货币名称显示
            cc.setFinacename1(config.getFinacename1());
            cc.setFinacename2(config.getFinacename2());
            cc.setFinacename3(config.getFinacename3());
            cc.setFinacename4(config.getFinacename4());
            cc.setCashcouponmul(config.getCashcouponmul());
        }
        if(isMoreAddress==0){
            addressService.updateAddressIsMoreAddressByUserId(userId);
        }
        List<Address> addresses=addressService.selectDefaultMore(1,userId);
//        if(addresses!=null&&addresses.size()>0){
//            Address address1=addresses.stream().filter(c ->(c.getIsdefault()!=null&&c.getIsdefault()==1)).collect(Collectors.toList()).get(0);
//            address=address1;
//            provinceId=address1.getProvinceId()==null?0:address1.getProvinceId();
//        }
        map.put("WebConfig",cc);
        map.put("isMoreAddress",isMoreAddress);
        map.put("addressCount",addressCount);
        map.put("productInfo",list);
        map.put("avgCoupon", df.format(avgCoupon1));//兑换券
        map.put("avgCashCoupon",df.format(avgCashCoupon1));//折扣券
        map.put("avgCoupons", avgCoupon1);
        map.put("avgCashCoupons",avgCashCoupon1);
        map.put("address",address);
        map.put("addressList",addresses);
        map.put("freight",freight);
        map.put("realPay",realPay);
        map.put("productNumber",productNumber);
        map.put("memberSave",memberSaveS);//会员节省
        map.put("realCashCouponAll",realCashCouponS);//总折扣券
        map.put("couponAll",couponS);//总兑换券
        map.put("count",list.size());//商品数量
        map.put("cartIds",CartIds);//购物车id
        map.put("backCashCoupon",backCashCoupon);//返回折扣券
        return map;
    }

    //获取重量
    public static Map<String,Object> getWeight(List<OrderDetailsProduct> list){
        Map<String,Object> map=new HashMap<>();
        double weight=0.0;
        if(list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                weight +=list.get(i).getProWeight();
            }
        }
        map.put("weight", weight);
        return map;
    }
    // 添加购物车
    public static Response addCartPub(Integer productId, Integer guigeId, Integer productCount,int userId) {
        String errorInfo="";
        if(productId==0){errorInfo="产品ID不能为空";}
        if(guigeId==0){errorInfo="规格ID不能为空";}
        if(productCount==0){errorInfo="产品数量不能为空";}
        //if(supplier==""){errorInfo="供货商不能为空";}
        //if(productPrice.equals(BigDecimal.ZERO)){errorInfo="产品价格不能为空";}
        if(errorInfo!=""){
            return new Response(MessageConstants.MSG_OPERATE_FAILED,-1,errorInfo);
        }
        System.out.println("productId:"+productId);
        Product product=productService.selectByPrimaryKey(productId);
        int ismoreaddress=product.getIsMoreAddress()==null?0:product.getIsMoreAddress();

        Cart cart = new Cart();
        cart.setProductId(productId);
        cart.setUserId(userId);
        cart.setProductCount(productCount);
        cart.setGuigeId(guigeId);
        //cart.setSupplier("公司");
        if(ismoreaddress==1){//活动产品的购物车直接为502 不展示给前端
            cart.setCartStatus("502");
        }else {
            cart.setCartStatus("501");
        }
        cart.setTime(new Date());
        cart.setType(2);
        //cart.setProductPrice(BigDecimal.valueOf(520));
        int res=cartService.insert(cart);
        Integer cartId=cart.getShoppingId();//获取增加的shoppingId

        return new Response(MessageConstants.MSG_SUCCESS,cartId,errorInfo);
    }

    // 更新购物车数量
    public static Response upCartPub(Integer shoppingId,Integer productCount) {
        Cart cart = cartService.selectByPrimaryKey(shoppingId);
        cart.setProductCount(productCount);
        int res=cartService.updateByPrimaryKey(cart);
        Integer cartId=cart.getShoppingId();//获取shoppingId

        return new Response(MessageConstants.MSG_SUCCESS,cartId,"");
    }

}
